import React,{Component} from 'react'
import {BrowserRouter,Link,Route,Switch,Redirect} from 'react-router-dom'
import {connect} from 'react-redux'
import {login,logout} from '../store'
import List from './List'

function PrivateRoute({component:Component,isLogin,...rest}){
  return (
    <Route
      {...rest}
      render={
        props=>
          isLogin ? (
            <Component {...props} />
          ) : (
            <Redirect
              to={{
                pathname:'/login',
                state:{redirect:props.location.pathname}
              }}
            />
          )
      }
    />
  )
}

function Login({location,isLogin,login}){
  const redirect=location.state.redirect || '/'
  if(isLogin) return <Redirect to={redirect} />
  return (
    <div>
      <button onClick={login}>登录</button>
    </div>
  )
}

const WrapperPrivateRoute=connect(
  (state)=>(
    {isLogin:state.user.isLogin}
  )
)(PrivateRoute)

const WrapperLogin=connect(
  (state)=>(
    {isLogin:state.user.isLogin}
  ),
  {
    login,
    logout
  }
)(Login)

export default class Router extends Component{
  render(){
    return (
      <BrowserRouter>
        <nav>
          <Link to='/'>首页</Link>
          <Link to='/list'>列表</Link>
        </nav>
        <Switch>
          <Route exact path='/' component={()=>(<div>首页</div>)} />
          {/* <Route path='/list' component={List} /> */}
          <WrapperPrivateRoute path='/list' component={List} />
          <Route path='/login' component={WrapperLogin} /> 
          <Route component={()=>(<div>页面不存在</div>)} />
        </Switch>
      </BrowserRouter>
    )
  }
}